<template>
  <basic-container>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-tabs type="border-card" class="informationLabel">
          <el-tab-pane label="标签生成">
            <avue-form :defaults.sync="defaults" class="newFormStyle" ref="form" key="3" v-model="model" :option="serialnoCreateOption" @submit="rawSerialNumberGenerate">
              <template slot="workOrderNo">
                <el-input placeholder="请选择 工单号" v-model="model.workOrderNo" class="input-with-select" disabled>
                  <el-button slot="append" icon="el-icon-circle-close" v-if="model.workOrderNo" @click="clearModel"></el-button>
                  <el-button slot="append" icon="el-icon-search" @click="openWorkorderCommonModal()"></el-button>
                </el-input>
              </template>
            </avue-form>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col :span="16">
        <el-tabs type="border-card" class="informationLabel">
          <el-tab-pane label="序列号规则演示">
            <div class="sequenceInfo">
              <table border="1">
                <tr>
                  <th colspan="4">序列号规则</th>
                </tr>
                <tr>
                  <th>规则名称</th>
                  <th>
                    <el-tooltip class="item" effect="dark" placement="top-start">
                      <i class="el-icon-info" style="color: #606266"></i>
                      <div slot="content">
                        [P]：前缀字符,[YY]：两位年份, [YYYY]：四位年份, [M]：月,<br />[W]：周, [D]：日, [S]：流水号, [N]：自定义字符。<br />[B]：后缀字符 <br />如：[YY][M][S][B]
                        <br />若无流水号则没有[S],例如：[YY][M][B]
                      </div>
                      <!-- <el-button style="padding: 0; font-size: 18px" type="info" icon="el-icon-info" circle></el-button> -->
                    </el-tooltip>
                    序列号规则
                    <el-button
                      v-if="
                        sequenceRuleInfo.sequenceNoFormat &&
                        (sequenceRuleInfo.sequenceNoFormat.indexOf('[YYYY]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[YY]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[M]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[D]') > -1)
                      "
                      style="padding: 5px"
                      type="primary"
                      icon="el-icon-edit"
                      circle
                      @click="openTimeConfigModel"
                    ></el-button>
                  </th>
                  <th>序列号规则位数</th>
                  <th>起始/结束流水（参考）</th>
                </tr>
                <tr style="height: 40px">
                  <td>{{ sequenceRuleInfo.name }}</td>
                  <td>
                    <div>{{ sequenceRuleInfo.sequenceNoFormat }}</div>
                    <div>{{ sequenceRuleInfo.sequenceNoFormatZh }}</div>
                  </td>
                  <td>
                    <div v-if="sequenceRuleInfo.charactersCount">配置长度:{{ sequenceRuleInfo.charactersCount }}</div>
                    <div v-if="sequenceRuleInfo.seqNoFormatDemo">
                      例:{{ sequenceRuleInfo.seqNoFormatDemo }}<span>(当前长度:{{ sequenceRuleInfo.seqNoFormatDemo.length }})</span>
                    </div>
                  </td>
                  <td>
                    {{ startSequenceNo ? startSequenceNo : startSequenceNumber ? startSequenceNumber : '' }}/{{
                      sequenceRuleInfo.endSequenceNo ? sequenceRuleInfo.endSequenceNo : ''
                    }}
                  </td>
                </tr>
              </table>
              <table class="generateSerialNoInfo" border="1">
                <tr>
                  <th colspan="4">序列号预览</th>
                </tr>
                <tr>
                  <div style="font-size: 15px; margin: 15px">序列号数量:{{ sequenceRuleInfo.quantity }}</div>
                  <div style="font-size: 15px; margin: 15px">起始序列号:{{ sequenceRuleInfo.sequenceNumberFrom }}</div>
                  <div style="font-size: 15px; margin: 15px">结尾序列号:{{ sequenceRuleInfo.sequenceNumberTo }}</div>
                </tr>
              </table>
              <el-row>
                <el-col :span="15">
                  <print-template ref="printInfo" :templateType="templateType" @getPrintInfo="getPrintInfo"></print-template>
                  <div style="display: flex; justify-content: flex-end">
                    <el-button type="primary" size="small" icon="el-icon-printer" @click="printTest">打印测试</el-button>
                    <el-button type="primary" size="small" icon="el-icon-printer" @click="batchPrinting">打印标签</el-button>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <el-tabs type="border-card" class="informationLabel">
      <el-tab-pane label="标签记录">
        <avue-crud
          v-show="model.workOrderNo"
          class="serialNoGenerationRecord"
          ref="serialNoGenerationRecord"
          :option="serialNoGenerationRecordOption"
          :data="serialnoDataByWorkOrder"
          @row-click="rowClick"
        >
          <template slot-scope="{ row }" slot="menu">
            <el-button icon="el-icon-printer" size="small" type="text" @click="Reprint(row)" :disabled="row.isPrinted !== 1 || row.generationType === 'SCRAP'">
              <span>重打</span>
            </el-button>
          </template>
        </avue-crud>
        <avue-crud
          v-show="!model.workOrderNo"
          class="serialNoGenerationRecord"
          ref="serialNoGenerationRecordByWorkOrder"
          :page.sync="page"
          :option="serialNoGenerationRecordOption"
          :data="serialnoData"
          @row-click="rowClick"
        >
          <template slot-scope="{ row }" slot="menu">
            <el-button icon="el-icon-printer" size="small" type="text" @click="Reprint(row)" :disabled="row.isPrinted == 0">
              <span>重打</span>
            </el-button>
          </template>
        </avue-crud>
      </el-tab-pane>
    </el-tabs>
    <!-- 操作日志 -->
    <operation-log ref="operationLog"></operation-log>
    <!-- 选择工单组件 -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <el-dialog append-to-body title="序列号规则时间修改" :visible.sync="timeConfigModel" width="30%">
      <avue-form ref="timeConfigForm" v-model="timeConfig" :option="timeConfigOption"> </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="onSaveTimeConfig"> <i class="el-icon-circle-plus-outline"></i><span>保 存</span> </el-button>
        <el-button size="small" @click="timeConfigModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <el-dialog append-to-body title="重打" v-if="printInfoModel" :visible.sync="printInfoModel" width="35%">
      <div style="display: flex; justify-content: center; margin-bottom: 10px">
        <span style="color: red">注：仅需修改流水号即可，重打的起始流水号和结束流水号需在原流水号范围内</span>
      </div>
      <avue-form ref="printForm" v-model="printInfo" :option="printInfoOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="printSubmit"><i class="el-icon-printer"></i><span>重打</span></el-button>
        <el-button size="small" @click="printInfoModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <print-time-input-form :visible.sync="printDialog" :other-info-option="otherInfoOption" @printInfo="(otherInfo) => handlePrintSequence(otherInfo)"></print-time-input-form>
  </basic-container>
</template>
<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import printTemplate from '@/views/product/components/printTemplate';
import { getSeqNoRules } from '@/util/global';
import { getYearWeek, focusInput, showSuccessLog, showFailLog, showWarningLog } from '@/util/helpers';
import {
  createSequence,
  getSourceListByWorkOrderId,
  getSourceList,
  sequencePrint,
  sequenceGenerationSum,
  printTest,
  snPrint,
  snPrintNoWorkOrder
} from '@/api/labelManagement/customerBarcodeCreate';
import { getDetail } from '@/api/admin/sequencedefinition';
import OperationLog from '@/components/operation-log/operation-log.vue';
import { getList as getAttributeConfigList } from '@/api/system/custom-attribute-config';
import { getLastPrintRecord } from '@/api/admin/barcode-record';
import { getPrintFormMixin } from '@/mixins/getPrintFormMixin';
import printTimeInputForm from '@/components/print-time-input-form';
export default {
  components: {
    CommonModalTemplate,
    printTemplate,
    OperationLog,
    printTimeInputForm
  },
  mixins: [getPrintFormMixin],
  data() {
    return {
      model: {}, //序列号生成信息
      serialnoCreateOption: {
        labelPosition: 'right',
        labelWidth: 130,
        // menuBtn: true,
        submitBtn: true,
        submitText: '生成序列号',
        emptyBtn: false,
        menuPosition: 'right',
        column: [
          {
            type: 'search',
            label: '工单号',
            prop: 'workOrderNo',
            span: 24,
            disabled: true,
            appendClick: () => {
              this.openWorkorderCommonModal();
            }
          },
          {
            label: '客户名称',
            prop: 'partnerName',
            span: 24,
            disabled: true,
            placeholder: '客户名称'
          },
          {
            label: '客户编码',
            prop: 'partnerCode',
            span: 24,
            disabled: true,
            placeholder: '客户编码'
          },
          {
            label: '产品编码',
            prop: 'partNo',
            span: 24,
            disabled: true,
            placeholder: '产品编码'
          },
          {
            label: '产品名称',
            prop: 'partName',
            span: 24,
            disabled: true,
            placeholder: '产品名称'
          },
          {
            label: '产品型号',
            prop: 'partModel',
            span: 24,
            disabled: true,
            placeholder: '产品型号'
          },
          {
            label: '生产总数',
            prop: 'quantity',
            span: 24,
            disabled: true,
            placeholder: '生产总数'
          },
          {
            type: 'search',
            label: '序列号规则',
            prop: 'sequenceName',
            span: 24,
            disabled: true,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ],
            appendClick: () => {
              this.openSerialnoCommonModal();
            }
          },
          {
            label: '本次生成数量',
            prop: 'produceQuantity',
            span: 24,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ]
          }
        ]
      }, //序列号生成信息配置内容
      timer: new Date().getTime(),
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      sequenceRuleInfo: {}, //产品序列号规则信息
      recordDefaults: {},
      serialNoGenerationRecordOption: {
        //工单产品序列号内容配置
        height: 300,
        calcHeight: 30,
        border: true,
        index: true,
        viewBtn: false,
        selection: false,
        dialogClickModal: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        tip: false,
        refreshBtn: false, //刷新按钮是否显示
        columnBtn: false, //控制表格列是否显示按钮是否显示
        menu: true,
        indexLabel: '序号',
        highlightCurrentRow: true,
        column: [
          {
            label: '起始序列号',
            prop: 'sequenceNumberFrom'
          },
          {
            label: '结尾序列号',
            prop: 'sequenceNumberTo'
          },
          {
            label: '序列号数量',
            prop: 'quantity'
          },
          {
            label: '生成时间',
            prop: 'createTime'
          },
          {
            label: '生成类型',
            prop: 'generationType',
            html: true,
            formatter: (val) => {
              switch (val.generationType) {
                case 'NORMAL':
                  return '正常';
                case 'SCRAP':
                  return '报废';
                case 'APPEND':
                  return '增补';
                case 'REPLACE':
                  return '置换';
                case 'REVORK':
                  return '撤销';
                default:
                  break;
              }
            }
          },
          {
            label: '状态',
            prop: 'isPrinted',
            html: true,
            formatter: (val) => {
              switch (val.isPrinted) {
                case 0:
                  return `<span class="text-yellow">未打印</span>`;
                case 1:
                  return `<span class="text-green">已打印</span>`;
                case 2:
                  return `<span class="text-red">部分打印</span>`;
                default:
                  return `<span class="text-red">报废</span>`;
                  break;
              }
            }
          }
        ]
      },
      serialnoDataByWorkOrder: [], //序列号生成记录
      serialnoData: [], //无工单号生成序列号记录
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      timeConfigModel: false, //序列号规则时间修改模态框是否显示
      timeConfig: {}, //序列号规则时间配置
      timeConfigOption: {
        //序列号规则时间修改内容配置
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '年代码',
            prop: 'year',
            type: 'year',
            format: 'yyyy',
            valueFormat: 'yyyy',
            span: 20,
            display: false
          },
          {
            label: '月代码',
            prop: 'month',
            type: 'month',
            format: 'MM',
            valueFormat: 'MM',
            span: 20,
            display: false
          },
          {
            label: '周代码',
            prop: 'week',
            span: 20,
            display: false
          },
          {
            label: '日代码',
            prop: 'day',
            type: 'date',
            format: 'dd',
            valueFormat: 'dd',
            span: 20,
            display: false,
            change(val) {
              console.log(val, Date.parse(val), Object.prototype.toString.call(Date.parse(val)));
            }
          }
        ]
      },
      printInfo: {}, //打印机打印模版信息
      defaults: {},
      selectionInfo: {}, //选中生成记录
      printWorkOrderId: '', //获取工单ID
      getRecordReceivingId: '',
      templateType: '', //需要过滤的标签模版类型
      startSequenceNumber: '', //起始序列号
      startSequenceNo: '', //预生成起始序列号
      printInfoModel: false,
      printInfo: {},
      printInfoOption: {
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '起始流水号',
            prop: 'sequenceNumberFrom',
            span: 20
          },
          {
            label: '结束流水号',
            prop: 'sequenceNumberTo',
            span: 20
          },
          {
            label: '标签模版',
            prop: 'labelTemplateName',
            span: 20,
            type: 'search',
            placeholder: '请选择 标签模板',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择标签模板',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLabelTemplateModal();
            }
          },
          {
            label: '打印机',
            prop: 'equipmentName',
            span: 20,
            type: 'search',
            placeholder: '请选择 打印机',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择打印机',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPrintersModal();
            }
          }
        ]
      },
      customAttributeList: []
    };
  },
  mounted() {
    this.getSequenceRecord();
    this.timeConfig.year = this.timeConfig.year ? this.timeConfig.year : this.$moment().format('YYYY');
    this.timeConfig.month = this.timeConfig.month ? this.timeConfig.month : this.$moment().format('MM');
    this.timeConfig.week = this.timeConfig.week ? this.timeConfig.week : getYearWeek();
    this.timeConfig.day = this.timeConfig.day ? this.timeConfig.day : this.$moment().format('DD');
  },
  methods: {
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 打开选择工单号模态框
     */
    async openWorkorderCommonModal() {
      this.modalName = 'workorderModal';
      this.tableOption = {
        modalTitle: '选择工单号（双击进行选择）',
        url: '/api/mes-product/work-order/page',
        isPage: true,
        rowSelectionType: 'single',
        searchLabelWidth: 100,
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true,
            searchType: 'input',
            type: 'search'
          },
          {
            label: '生产工单',
            prop: 'workOrderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'type',
            span: 8,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=order_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '工单数量',
            prop: 'planQuantity',
            type: 'number',
            minRows: 1
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            search: true,
            searchType: 'input',
            type: 'search'
          },
          {
            label: '产品名称',
            prop: 'productPartName',
            search: true
          },
          {
            label: '产品规格',
            prop: 'productPartModel',
            search: true
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion',
            type: 'search'
          },
          {
            label: '计划开始时间',
            prop: 'planStartTime',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '计划结束时间',
            prop: 'planEndTime',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '制定人',
            prop: 'creator',
            disabled: true
          },
          {
            label: '状态',
            prop: 'status',
            span: 8,
            type: 'select',
            dataType: 'string',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=mfg_work_order'
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea'
          }
        ]
      };
      // let path = this.$route.path;
      // await getAttributeConfigList(path).then((res) => {
      //   this.customAttributeList = this._get(res, 'data.data', []);
      //   this._forEach(this.customAttributeList, (item, index) => {
      //     this.tableOption.columnDefs.splice(11, 0, {
      //       label: item.lableCnName,
      //       prop: item.attributeKey,
      //       type: item.controlType,
      //       value: item.defaultValue,
      //       dispaly: item.enabled,
      //       search: index != 1 ? true : false
      //     });
      //   });
      //   //   this.$refs.crud.refreshTable();
      // });
      this.$refs.commonModalTemplate.showModal();
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'workorderModal':
          this.printWorkOrderId = this._get(rowData, 'id', '');
          this.model.workOrderId = this._get(rowData, 'id', '');
          this.model.workOrderNo = this._get(rowData, 'workOrderNo', '');
          // this.model.partnerName = this._get(rowData, 'partnerName', '');
          // this.model.partnerCode = this._get(rowData, 'partnerCode', '');
          this.model.partNo = this._get(rowData, 'productPartNo', '');
          this.model.partName = this._get(rowData, 'productPartName', '');
          this.model.partModel = this._get(rowData, 'productPartModel', '');
          // this.model.sequenceDefinitionId = this._get(rowData, 'productSequenceDefinitionId', '');
          // this.model.sequenceName = this._get(rowData, 'sequenceDefinitionName', '');
          this.model.quantity = this._get(rowData, 'planQuantity', '');
          this.printInfo.labelTemplateId = this._get(rowData, 'labelTemplateId', '');
          this.$refs.printInfo.model.labelTemplateName = this._get(rowData, 'labelTemplateName', '');
          if (this.model.sequenceDefinitionId) {
            this.getSequencedefinitionDetail(this.model.sequenceDefinitionId);
            // this.getStartOrEndSequenceNumber(this.model.sequenceDefinitionId);
          }
          this.getSequenceRecordById(this._get(rowData, 'id', ''));
          break;
        case 'serialnoModal':
          this.model.sequenceDefinitionId = this._get(rowData, 'id', '');
          this.model.sequenceName = this._get(rowData, 'name', '');
          // this.getStartOrEndSequenceNumber(this.model.sequenceDefinitionId);
          this.sequenceRuleInfo.id = this._get(rowData, 'id', '');
          this.getSequencedefinitionDetail(this.sequenceRuleInfo.id);
          this.seqNoConvert();
          break;
        case 'printersModal':
          this.printInfo.equipmentId = this._get(rowData, 'id', '');
          this.printInfo.equipmentName = this._get(rowData, 'name', '');
          break;
        case 'labelTemplateModal':
          this.printInfo.labelTemplateId = this._get(rowData, 'id', '');
          this.printInfo.labelTemplateName = this._get(rowData, 'name', '');
          break;
        default:
          break;
      }
    },
    /**
     * 根据序列号规则ID查询详情
     */
    getSequencedefinitionDetail(sequencedefinitionId) {
      getDetail(sequencedefinitionId).then((res) => {
        this.$set(this.sequenceRuleInfo, 'name', this._get(res, 'data.data.name', ''));
        this.$set(this.sequenceRuleInfo, 'sequenceNoFormat', this._get(res, 'data.data.sequenceNoFormat', ''));
        this.$set(this.sequenceRuleInfo, 'sequenceNoFormatZh', this._get(res, 'data.data.sequenceNoFormatZh', ''));
        this.$set(this.sequenceRuleInfo, 'seqNoFormatDemo', this._get(res, 'data.data.seqNoFormatDemo', ''));
        this.$set(this.sequenceRuleInfo, 'containsSequenceNo', this._get(res, 'data.data.containsSequenceNo', true));
        this.$set(this.sequenceRuleInfo, 'charactersCount', this._get(res, 'data.data.charactersCount', 0));
        let isPregenerated = this._get(res, 'data.data.isPregenerated', '');
        if (isPregenerated) {
          this.startSequenceNo = this._get(res, 'data.data.used', '');
          this.$set(this.sequenceRuleInfo, 'endSequenceNo', this._get(res, 'data.data.total', ''));
        } else {
          this.startSequenceNo = '';
          this.$set(this.sequenceRuleInfo, 'endSequenceNo', this._get(res, 'data.data.endSequenceNo', ''));
        }
        this.seqNoConvert();
      });
    },
    /**
     * 打开序列号规则选择模态框
     */
    openSerialnoCommonModal() {
      this.modalName = 'serialnoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择序列号规则（双击进行选择）',
        url: '/api/mes-admin/sequencedefinition/page?type=MATERIAL&subType=WORK_IN_PROGRESS',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '规则名称',
            prop: 'name',
            search: true
          },
          {
            label: '规则编码',
            prop: 'code',
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '起始流水号',
            prop: 'startSequenceNo'
          },
          {
            label: '结束流水号',
            prop: 'endSequenceNo'
          },
          {
            label: '清零类型',
            prop: 'regressionType',
            type: 'select',
            dicData: [
              {
                label: '不清零',
                value: ''
              },
              {
                label: '年',
                value: 'yearType'
              },
              {
                label: '月',
                value: 'monthType'
              },
              {
                label: '周',
                value: 'weekType'
              },
              {
                label: '日',
                value: 'dayType'
              }
            ]
          },
          {
            label: '序列号构成规则',
            prop: 'sequenceNoFormat'
          }
        ]
      };
    },
    /**
     * 序列号规则转换中文
     * @param sequenceNoValue 序列号规则
     * @param sequenceNo 序列号规则起始流水号
     */
    seqNoConvert() {
      let seqNoRules = [];
      this._forEach(getSeqNoRules(), (item) => {
        seqNoRules = [...seqNoRules, ...item.value];
      });
      let splitList = this.sequenceRuleInfo.sequenceNoFormat.split('');
      //在[前加空格  ]后加空格
      splitList = splitList.map((item) => {
        if (item === '[') {
          return ' [';
        } else if (item === ']') {
          return '] ';
        } else {
          return item;
        }
      });
      splitList = splitList.join('');
      //按空格拆分字符串
      splitList = splitList.split(' ');
      //匹配中文
      console.log(splitList);
      console.log(seqNoRules);
      let splitArr = this._map(splitList, (item) => {
        this._forEach(seqNoRules, (ele) => {
          if (item === ele.key) {
            item = ele.value;
          }
        });
        return item;
      });
      //去除空格
      splitArr = splitArr.filter(function (s) {
        return s && s.trim();
      });
      //转换后给序列号规则赋值
      this.sequenceRuleInfo.sequenceNoFormatZh = splitArr.join('+');

      let splitDemoArr = this._map(splitList, (item) => {
        this._forEach(seqNoRules, (ele) => {
          if (item === ele.key) {
            let currentDate = new Date();
            switch (item) {
              case '[YY]':
                let year = String(currentDate.getFullYear());
                item = year.substring(2, year.length);
                break;
              case '[YYYY]':
                item = currentDate.getFullYear();
                break;
              case '[M]':
                let month = currentDate.getMonth() + 1;
                if (month < 10) {
                  item = '0' + month;
                } else {
                  item = month;
                }
                break;
              case '[W]':
                let today = new Date();
                let firstDay = new Date(today.getFullYear(), 0, 1);
                let dayOfWeek = firstDay.getDay();
                let spendDay = 1;
                if (dayOfWeek != 0) {
                  spendDay = 7 - dayOfWeek + 1;
                }
                firstDay = new Date(today.getFullYear(), 0, 1 + spendDay);
                let d = Math.ceil((today.valueOf() - firstDay.valueOf()) / 86400000);
                let week = Math.ceil(d / 7);
                week = week + 1;
                if (week < 10) {
                  item = '0' + week;
                } else {
                  item = week;
                }
                break;
              case '[D]':
                let day = currentDate.getDate();
                if (day < 10) {
                  item = '0' + day;
                } else {
                  item = day;
                }
                break;
              case '[S]':
                if (this.sequenceRuleInfo.sequenceNo) {
                  item = this.sequenceRuleInfo.sequenceNo;
                } else {
                  item = this.sequenceRuleInfo[ele.code];
                }
                break;
              case '[WO]':
                if (this.model.workOrderNo) {
                  item = this.model.workOrderNo;
                } else {
                  item = '[WO]';
                }
                break;
              default:
                if (ele.code) {
                  item = this.sequenceRuleInfo[ele.code];
                }
                break;
            }
          }
        });
        return item;
      });
      splitDemoArr = splitDemoArr.filter(function (item) {
        return String(item) && String(item).trim();
      });
      this.sequenceRuleInfo.seqNoFormatDemo = splitDemoArr.join('');
    },
    /**
     * 序列号规则时间修改
     */
    openTimeConfigModel() {
      this.timeConfigModel = true;
      this.timeConfig.year = this.timeConfig.year ? this.timeConfig.year : this.$moment().format('YYYY');
      this.timeConfig.month = this.timeConfig.month ? this.timeConfig.month : this.$moment().format('MM');
      this.timeConfig.week = this.timeConfig.week ? this.timeConfig.week : getYearWeek();
      this.timeConfig.day = this.timeConfig.day ? this.timeConfig.day : this.$moment().format('DD');
      this.$nextTick(() => {
        let column = this.$refs.timeConfigForm.option.column;
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YYYY]') > -1 || this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YY]') > -1) {
          let year = this.findObject(column, 'year');
          year.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[M]') > -1) {
          let month = this.findObject(column, 'month');
          month.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1) {
          let week = this.findObject(column, 'week');
          week.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1) {
          let week = this.findObject(column, 'week');
          week.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[D]') > -1) {
          let day = this.findObject(column, 'day');
          day.display = true;
        }
      });
    },
    /**
     * 序列号规则中时间修改保存
     */
    onSaveTimeConfig() {
      //验证是否传递序列号规则中年份日期
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YYYY]') > -1 || this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YY]') > -1) {
        if (!this.timeConfig.year) {
          this.$message({
            type: 'error',
            message: '请选择序列号规则中的年份！'
          });
          return;
        }
      }
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[M]') > -1) {
        if (!this.timeConfig.month) {
          this.$message({
            type: 'error',
            message: '请选择序列号规则中的月份！'
          });
          return;
        }
      }
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1) {
        if (!this.timeConfig.week) {
          this.$message({
            type: 'error',
            message: '请输入序列号规则中的周数！'
          });
          // Helpers.selectInput('week');
          return;
        }
      }
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[D]') > -1) {
        if (!this.timeConfig.day) {
          this.$message({
            type: 'error',
            message: '请选择序列号规则中的日期！'
          });
          return;
        }
      }
      this.timeConfigModel = false;
    },
    /**
     * 产品序列号生成
     */
    rawSerialNumberGenerate(row, done) {
      if (!row.sequenceName) {
        this.$message({
          type: 'warning',
          message: '请选择序列号规则!'
        });
        done();
        return;
      }
      if (!row.produceQuantity) {
        this.$message({
          type: 'warning',
          message: '请输入本次生成数量!'
        });
        done();
        return;
      }
      let reg = /^[1-9]\d*$/g;
      if (!reg.test(row.produceQuantity)) {
        this.$message({
          type: 'warning',
          message: '生成数量为正整数!'
        });
        done();
        return;
      }
      if (this.model.workOrderNo) {
        let attr = {
          workOrderId: this.model.workOrderId,
          quantity: row.produceQuantity,
          sequenceDefinitionId: this.model.sequenceDefinitionId,
          timeConfig: this.timeConfig
        };
        createSequence(attr).then(
          (res) => {
            if (res.data.data.options && res.data.data.options != null) {
              let options = JSON.parse(res.data.data.options);
              if (options.isWarning) {
                this.$message({
                  type: 'warning',
                  message: `${res.data.msg}，可用码段不足${options.warningQuantity}，剩余${options.availableQuantity}，请联系相关人员购买！`
                });
                showWarningLog(`${res.data.msg}，可用码段不足${options.warningQuantity}，剩余${options.availableQuantity}，请联系相关人员购买！`);
              } else {
                this.$message({
                  type: 'success',
                  message: res.data.msg
                });
                showSuccessLog(res.data.msg);
              }
            }
            this.getSequenceRecordById(this.model.workOrderId);
            // this.getStartOrEndSequenceNumber(this.model.sequenceDefinitionId);
            done();
          },
          (error) => {
            showFailLog(error.data.msg);
            done();
          }
        );
      } else {
        let attr = {
          quantity: row.produceQuantity,
          sequenceDefinitionId: this.model.sequenceDefinitionId,
          timeConfig: this.timeConfig
        };
        createSequence(attr).then(
          (res) => {
            if (res.data.data.options && res.data.data.options != null) {
              let options = JSON.parse(res.data.data.options);
              if (options.isWarning) {
                this.$message({
                  type: 'warning',
                  message: `${res.data.msg}，可用码段不足${options.warningQuantity}，剩余${options.availableQuantity}，请联系相关人员购买！`
                });
                showWarningLog(`${res.data.msg}，可用码段不足${options.warningQuantity}，剩余${options.availableQuantity}，请联系相关人员购买！`);
              } else {
                this.$message({
                  type: 'success',
                  message: res.data.msg
                });
                showSuccessLog(res.data.msg);
              }
            }
            this.getSequenceRecord();
            // this.getStartOrEndSequenceNumber(this.model.sequenceDefinitionId);
            done();
          },
          (error) => {
            showFailLog(error.data.msg);
            done();
          }
        );
      }
    },
    /**
     * 根据id获取产品序列号生成记录
     */
    getSequenceRecordById(id) {
      let params = {
        sourceId: id,
        sourceType: 'PRODUCT_PARTNER'
      };
      getSourceListByWorkOrderId(params).then(
        (res) => {
          this.serialnoDataByWorkOrder = this._get(res, 'data.data', []);
        },
        (error) => {
          this.serialnoDataByWorkOrder = [];
        }
      );
    },
    /**
     * 无工单获取序列号生成记录
     */
    getSequenceRecord() {
      let params = {
        sourceType: 'PRODUCT_PARTNER',
        sourceId: -1,
        current: this.page.currentPage,
        size: this.page.pageSize
      };
      getSourceList(params).then(
        (res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.serialnoData = data.records;
          //   this.selectionClear();
        },
        (error) => {
          this.serialnoData = [];
        }
      );
    },
    /**
     * 获取生成包装条码记录
     */
    getPackingSequenceRecord() {
      let params;
      if (this.labelPrintType === 'packIdCreate') {
        params = {
          sourceId: this.packIdCreateForm.workOrderId,
          productPackingDetailId: this.packIdCreateForm.packingConfigDetailId
        };
      } else if (this.labelPrintType === 'packIdAppend') {
        params = {
          sourceId: this.packIdAppendForm.workOrderId,
          productPackingDetailId: this.packIdAppendForm.packingConfigDetailId
        };
      }
      getSequenceGenerationSource(params).then(
        (res) => {
          this.serialnoDataByWorkOrder = this._get(res, 'data.data', []);
          // let generatedQuantity = 0;
          // this._forEach(this.serialnoDataByWorkOrder, (item) => {
          //     generatedQuantity = generatedQuantity + item.quantity;
          // });
          // this.model.surplusQuantity = this.model.quantity - generatedQuantity;
        },
        (error) => {
          this.serialnoDataByWorkOrder = [];
        }
      );
    },
    /**
     * 表格选中列表
     */
    rowClick(row) {
      this.selectionInfo = row;
      this.$refs.serialNoGenerationRecord.setCurrentRow(row);
    },
    /**
     * 获取打印机和打印模版信息
     */
    getPrintInfo(printInfo) {
      if (printInfo.printersId) {
        this.printInfo.printersId = printInfo.printersId;
      }
      if (printInfo.labelTemplateId) {
        this.printInfo.labelTemplateId = printInfo.labelTemplateId;
        const dataId = printInfo.dataId;
        if (dataId) {
          this.getDetail(printInfo.dataId);
        } else {
          this.fieldList = [];
        }
      }
    },
    getStartOrEndSequenceNumber(sequenceDefinitionId) {
      let params = {
        sourceId: this.printWorkOrderId,
        sequenceDefinitionId: sequenceDefinitionId
      };
      sequenceGenerationSum(params).then(
        (res) => {
          this.startSequenceNumber = this._get(res, 'data.data', '');
        },
        (error) => {
          this.startSequenceNumber = '';
        }
      );
    },
    clearModel() {
      this.model = {};
      this.$refs.form.resetFields();
      getSequenceRecord();
    },
    /**
     * 打印测试
     */
    printTest() {
      if (!this.printInfo.printersId) {
        this.$message({
          type: 'warning',
          message: '请选择打印机！'
        });
        return;
      }
      if (!this.printInfo.labelTemplateId) {
        this.$message({
          type: 'warning',
          message: '请选择标签模版！'
        });
        return;
      }
      if (this.model.workOrderId && this.serialnoDataByWorkOrder.length === 0) {
        this.$message.warning('请先生成标签记录！');
        return;
      }
      if (!this.model.workOrderId && this.serialnoData.length === 0) {
        this.$message.warning('请先生成标签记录！');
        return;
      }
      let params = {
        printId: this.printInfo.printersId,
        labelTemplateId: this.printInfo.labelTemplateId,
        workOrderId: this.model.workOrderId,
        sequenceNumber: this.model.workOrderNo ? this.serialnoDataByWorkOrder[0].sequenceNumberFrom : this.serialnoData[0].sequenceNumberFrom
      };
      printTest(params).then(
        (res) => {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          showSuccessLog(res.data.msg);
          if (this.model.workOrderNo) {
            this.getSequenceRecord();
          } else {
            this.getSequenceRecordById(this.model.workOrderId);
          }
        },
        (error) => {
          showFailLog(error.data.msg);
        }
      );
    },
    /**
     * 标签打印
     */
    batchPrinting() {
      if (!this.printInfo.printersId) {
        this.$message({
          type: 'warning',
          message: '请选择打印机！'
        });
        return;
      }
      if (!this.printInfo.labelTemplateId) {
        this.$message({
          type: 'warning',
          message: '请选择标签模版！'
        });
        return;
      }
      if (!Object.keys(this.selectionInfo).length) {
        this.$message({
          type: 'warning',
          message: '请选择一条生产记录'
        });
        return;
      }
      if (this.selectionInfo.isPrinted != 0) {
        this.$message.warning('请选择未打印的记录！');
        return;
      }
      let list = [];
      this._forEach(this.selectionList, (item) => {
        list.push(item.id);
      });
      if (!this.fieldList.length) {
        this.handlePrintSequence();
      } else {
        // 当标签模版绑定了数据源且设置了数据 打开其他信息弹窗
        this.printDialog = true;
      }
    },
    handlePrintSequence(otherInfo = {}) {
      if (this.model.workOrderId) {
        let params = {
          equipmentId: this.printInfo.printersId,
          labelTemplateId: this.printInfo.labelTemplateId,
          workOrderId: this.model.workOrderId,
          sequenceGenerationId: this._get(this.selectionInfo, 'id', '')
        };
        if (Object.keys(otherInfo).length) {
          params.extFields = JSON.stringify(otherInfo);
        }
        sequencePrint(params).then(
          (res) => {
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            showSuccessLog(res.data.msg);
            this.getSequenceRecordById(this.model.workOrderId);
          },
          (error) => {
            showFailLog(error.data.msg);
          }
        );
      } else {
        let params = {
          printId: this.printInfo.printersId,
          labelTemplateId: this.printInfo.labelTemplateId,
          sequenceGenerationId: this._get(this.selectionInfo, 'id', '')
        };
        if (Object.keys(otherInfo).length) {
          params.extFields = JSON.stringify(otherInfo);
        }
        snPrintNoWorkOrder(params).then(
          (res) => {
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            showSuccessLog(res.data.msg);
            this.getSequenceRecord();
          },
          (error) => {
            showFailLog(error.data.msg);
          }
        );
      }
    },
    async Reprint(row) {
      if (row.isPrinted !== 1) {
        this.$message.warning('已打印状态的才可以重打');
        return;
      }
      try {
        const printer = await this.getDefaultPrinter(row.id);
        const { labelTemplateId = '', equipmentId = '', equipmentName = '', labelTemplateName = '' } = printer;
        this.printInfo = {
          labelTemplateId: labelTemplateId,
          labelTemplateName: labelTemplateName,
          equipmentId: equipmentId,
          equipmentName
        };
      } catch (e) {
        console.warn(e);
      }
      this.printInfo.sequenceNumberFrom = row.sequenceNumberFrom;
      this.printInfo.sequenceNumberTo = row.sequenceNumberTo;
      this.printInfo.generationId = row.id;
      this.printInfoModel = true;
    },
    async getDefaultPrinter(id) {
      try {
        const res = await getLastPrintRecord({ generationId: id });
        return res.data.data;
      } catch (e) {
        console.warn(e);
      }
    },
    /**
     * 打印
     */
    printSubmit() {
      this.$refs.printForm.validate((valid, done) => {
        this.printInfo.fromSequenceNumber = this._cloneDeep(this.printInfo.sequenceNumberFrom);
        this.printInfo.toSequenceNumber = this._cloneDeep(this.printInfo.sequenceNumberTo);
        let params = {
          fromSequenceNumber: this.printInfo.fromSequenceNumber,
          toSequenceNumber: this.printInfo.toSequenceNumber,
          generationId: this.printInfo.generationId,
          labelTemplateId: this.printInfo.labelTemplateId,
          equipmentId: this.printInfo.equipmentId
        };
        if (valid) {
          snPrint(params).then(
            (res) => {
              this.$refs.printForm.resetFields();
              this.printInfoModel = false;
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              done();
            },
            (error) => {
              done();
            }
          );
        }
      });
    },
    /**
     * 获取打印机
     */
    openPrintersModal() {
      this.modalName = 'printersModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择打印机（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '打印机编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 110
          },
          {
            label: '打印机名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 110
          }
        ]
      };
    },
    /**
     * 打开标签模板模态框
     */
    openLabelTemplateModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模版（双击进行选择）',
        url: '/api/mes-admin/labeltemplate/page?is_latest=true&status=1',
        isPage: true,
        rowSelectionType: 'single',
        searchMenuSpan: 24,
        columnDefs: [
          {
            label: '大类',
            prop: 'type',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=sysSerial',
            cascader: ['subType'],
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            search: true
          },
          {
            label: '小类',
            prop: 'subType',
            dicUrl: '/api/blade-system/dict/dictionary?code={{key}}',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            type: 'select',
            search: true
          },
          {
            label: '模版名称',
            prop: 'fileName',
            search: true
          },
          {
            label: '模版代码',
            prop: 'code',
            search: true
          },
          {
            label: '版本名称',
            prop: 'revision'
          },
          {
            label: '客户/供应商',
            prop: 'clientName'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl'
          },
          {
            label: '标签地址',
            prop: 'fileUrl'
          },
          {
            label: '打印列数',
            prop: 'columnCount'
          },
          {
            label: '打印份数',
            prop: 'copies'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.sequenceInfo {
  table {
    width: 100%;
    height: auto;
    margin-bottom: 10px;
    font-size: 14px;
    th {
      border: 1px solid #ebeef5;
      background: #fafafa;
      height: 30px;
    }
    tr {
      border: 1px solid #ebeef5;
    }
    td {
      border: 1px solid #ebeef5;
      height: auto;
      text-align: center;
    }
    p {
      margin-left: 30px;
    }
  }
}
.newFormStyle {
  ::v-deep .el-form-item--small.el-form-item {
    margin-bottom: 5px;
  }
  ::v-deep .el-input--small input {
    height: 30px;
    line-height: 30px;
  }
}
.generateSerialNoInfo {
  div {
    margin: 5px 10px;
  }
}
.printButton {
  text-align: right;
}
.informationLabel {
  ::v-deep .avue-crud__menu {
    display: none;
  }
}
</style>
